package com.asen.libcommon.base.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle

/**
 * @date   : 2021/3/26
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : 封装 ViewPager2 适配器, T 泛型不要直接设置 Fragment ; 会爆内存泄漏
 */
class BaseFragmentStateAdapter<T> : FragmentStateAdapter {

    var mList: MutableList<T> = mutableListOf()
    private var mCreateView: ((position: Int, t: T) -> Fragment)

    constructor(
        fragmentManager: FragmentManager,
        lifecycle: Lifecycle,
        createView: ((position: Int, t: T) -> Fragment)
    ) : super(fragmentManager,lifecycle) {
        mCreateView = createView
    }

    override fun getItemCount(): Int = mList.size

    override fun createFragment(position: Int): Fragment {
        return mCreateView.invoke(position, mList[position])
    }

    fun addData(data: MutableList<T>?) {
        if (data == null) return
        mList.addAll(data)
        notifyDataSetChanged()
    }

    fun addData(data: T?) {
        if (data == null) return
        mList.add(data)
        notifyItemChanged(mList.size)
    }

    fun setNewDate(data: MutableList<T>?) {
        if (data == null) return
        mList.clear()
        mList.addAll(data)
        notifyDataSetChanged()
    }


}